package com.ddc.study.feature.query;

import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;

import com.ddc.study.R;
import com.ddc.study.base.BaseActivity;
import com.ddc.study.databinding.ActivityQueryBinding;
import com.ddc.study.entity.HotKey;
import com.ddc.study.view.VerticalDecoration;
import com.google.android.material.chip.Chip;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * Created on 2018/4/28.
 *
 * @author lshun
 * @version 1.0
 */
public class QueryActivity extends BaseActivity {
    private ActivityQueryBinding mBinding;
    private QueryViewModel mViewModel;
    private QueryHistoryAdapter mQueryHistoryAdapter = new QueryHistoryAdapter();
    private QueryResultAdapter mQueryResultAdapter = new QueryResultAdapter();

    @Override
    protected int getLayoutRes() {
        return -1;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ViewModelProvider.Factory factory = new SavedStateViewModelFactory(getApplication(), this);
        mViewModel = ViewModelProviders.of(this, factory).get(QueryViewModel.class);

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_query);
        mBinding.setLifecycleOwner(this);
        mBinding.setViewModel(mViewModel);

        mBinding.ivBack.setOnClickListener(v -> onBackPressed());

        mBinding.edtQueryWord.setOnEditorActionListener((v, actionId, event) -> {
            Log.e(TAG, "onEditorAction -> v = " + v + ", actionId = " + actionId + ", event = " + event);
            mBinding.ivSearch.performClick();
            return false;
        });

        mBinding.ivSearch.setOnClickListener(v -> {
            //mViewModel.setShowQueryResult(true);
            @Nullable Editable editable = mBinding.edtQueryWord.getText();
            if (editable == null || editable.length() == 0) {
                showToast(R.string.tips_empty_query_word);
                mBinding.edtQueryWord.requestFocus();
            } else {
                @NonNull String queryWord = editable.toString();
                mViewModel.setQueryWord(queryWord);
            }
        });

        mViewModel.getHotKeyLiveData().observe(this, hotKeys -> {
            mBinding.chipGroupHotKey.removeAllViews();
            if (hotKeys == null) {
                mBinding.chipGroupHotKey.setVisibility(View.GONE);
                return;
            }
            mBinding.chipGroupHotKey.setVisibility(View.VISIBLE);
            for (HotKey hotKey : hotKeys) {
                Chip chip = (Chip) getLayoutInflater()
                        .inflate(R.layout.layout_chip, mBinding.chipGroupHotKey, false);
                chip.setText(hotKey.getName());
                chip.setOnClickListener(view -> {
                    mBinding.edtQueryWord.setText(hotKey.getName());
                    mBinding.ivSearch.performClick();
                });
                mBinding.chipGroupHotKey.addView(chip);
            }
        });

        mBinding.recyclerViewQueryHistory.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recyclerViewQueryHistory.addItemDecoration(new VerticalDecoration(this));
        mBinding.recyclerViewQueryHistory.setAdapter(mQueryHistoryAdapter);
        mViewModel.getQueryHistoryPagedListLiveData(this)
                .observe(this, mQueryHistoryAdapter::submitList);

        mBinding.recyclerViewQueryResult.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recyclerViewQueryResult.addItemDecoration(new VerticalDecoration(this));
        mBinding.recyclerViewQueryResult.setAdapter(mQueryResultAdapter);
        mViewModel.getQueryResultPagedListLiveData("")
                .observe(this, mQueryResultAdapter::submitList);

        /*mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                mPage = 0;
                mPresenter.queryWord(mPage, query);
                hideSoftInput();
                switchToQueryResult();
                mQueryResultAdapter.setEmptyView(R.layout.layout_loading, mQueryResultRecyclerView);
                mQueryResultAdapter.setNewData(null);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //搜索框内容更新后清除搜索记录 重置分页信息
                mQueryResultAdapter.setNewData(null);
                mPage = 0;
                //隐藏提示信息
                if (mQueryResultAdapter.getEmptyView() != null)
                    mQueryResultAdapter.getEmptyView().setVisibility(View.GONE);
                //如果搜索框无内容就切换到显示热词和历史的页面
                if (newText == null || newText.isEmpty()) {
                    switchToHistory();
                }
                return false;
            }
        });

        mHistoryRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mHistoryRecyclerView.addItemDecoration(new VerticalDecoration(this));
        mHistoryAdapter.bindToRecyclerView(mHistoryRecyclerView);
        mHistoryAdapter.setOnItemClickListener((adapter, view, position) -> {
            History history = mHistoryAdapter.getItem(position);
            if (history == null) return;
            //点击搜索历史项直接提交搜索
            mSearchView.setQuery(history.getSearchWord(), true);
        });
        mHistoryAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            History history = mHistoryAdapter.getItem(position);
            if (history == null) return;
            mPresenter.deleteWord(history.getSearchWord());
        });

        mQueryResultRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mQueryResultRecyclerView.addItemDecoration(new VerticalDecoration(this));
        mQueryResultAdapter.bindToRecyclerView(mQueryResultRecyclerView);
        mQueryResultAdapter.setOnItemClickListener((adapter, view, position) -> {
            Article article = mQueryResultAdapter.getItem(position);
            if (article == null) return;
            HtmlActivity.openUrl(QueryActivity.this, article.getLink());
        });
        mQueryResultAdapter.setPreLoadNumber(5);
        mQueryResultAdapter.setOnLoadMoreListener(() -> mPresenter.queryWord(mPage, mSearchView.getQuery().toString()), mQueryResultRecyclerView);

        mPresenter.loadHotKey();
        mPresenter.loadHistory();*/
    }

    /*@Override
    public void onBackPressed() {
        Log.e(TAG, "back press");
        if (mQueryResultLayout.getVisibility() == View.VISIBLE) {
            switchToHistory();
            mQueryResultAdapter.setNewData(null);
        } else {
            super.onBackPressed();
        }
    }*/

    /*public void showHotKeyData(@Nullable List<HotKey> data) {
        if (data == null) {
            //TODO 是否要隐藏HotKey视图
            return;
        }
        mChipGroup.removeAllViews();
        Chip chip;
        for (final HotKey key : data) {
            chip = (Chip) View.inflate(this, R.layout.layout_chip, null);
            chip.setText(key.getName());
            chip.setOnClickListener(view -> mSearchView.setQuery(key.getName(), true));
            mChipGroup.addView(chip);
        }
    }

    public void showHistoryData(@Nullable List<History> data) {
        if (data == null || data.isEmpty()) {
            mHistoryCard.setVisibility(View.GONE);
            return;
        }

        mHistoryCard.setVisibility(View.VISIBLE);
        mHistoryAdapter.setNewData(data);
    }

    public void showQueryData(@Nullable MainData<Article> data) {
        Log.e(TAG, "showQueryData -> " + data);
        switchToQueryResult();
        if (data == null) {
            if (mQueryResultAdapter.isLoading()) {
                mQueryResultAdapter.loadMoreFail();
            } else {
                View v = getLayoutInflater().inflate(R.layout.layout_load_failed, mQueryResultRecyclerView, false);
                //v.setOnClickListener(view -> query());
                mQueryResultAdapter.setEmptyView(v);
            }
        } else {
            //mPage++;
            List<Article> articles = data.getData();
            if (articles != null) {
                mQueryResultAdapter.addData(articles);
            }

            if (data.isDataLoadOver()) {
                mQueryResultAdapter.loadMoreEnd();
            } else {
                mQueryResultAdapter.loadMoreComplete();
            }
        }
    }

    public void showDeleteWordResult(boolean success) {
        if (success) {
            //mPresenter.loadHistory();
        } else {
            showToast("删除失败~!");
        }
    }

    public void showDeleteAllWordsResult(boolean success) {
        if (success) {
            //不重新查询直接清空
            showHistoryData(null);
        } else {
            showToast("删除失败~!");
        }
    }

    private void switchToQueryResult() {
        mHistoryLayout.setVisibility(View.GONE);
        mQueryResultLayout.setVisibility(View.VISIBLE);
    }

    private boolean isQueryResultShowing() {
        return mQueryResultLayout.getVisibility() == View.VISIBLE;
    }

    private void switchToHistory() {
        mQueryResultLayout.setVisibility(View.GONE);
        mHistoryLayout.setVisibility(View.VISIBLE);
    }

    private boolean isHistoryShowing() {
        return mHistoryLayout.getVisibility() == View.VISIBLE;
    }*/
}
